package com.azzaou.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.azzaou.model.Chantier;
import com.azzaou.model.Client;
import com.azzaou.service.IClientService;
import com.azzaou.util.ErrorHandler;
import com.azzaou.util.ExportUtil;

public class ClientController implements Serializable {

	private static final long serialVersionUID = 1L;
	Client client;
	IClientService clientService;
	ErrorHandler errorHandler;
    private List<Client> listClients;
    private List<SelectItem> listNomComplet;
	private ExternalContext context ;
	private HttpServletRequest request;
	String action = "";
	boolean upload = false;
	private List<SelectItem> listTypes;
	
	public String filter()
	{
		listClients = clientService.getClientByCriteria(client);
		action = "filter";
		return "";
	}
	
	
	public List<SelectItem> getListTypes() {
		listTypes = new ArrayList<SelectItem>();
		listTypes.add(new SelectItem(client.getType(), client.getTypeValue()));
		listTypes.add(new SelectItem("E", "External"));
		listTypes.add(new SelectItem("C", "Chantier"));
		return listTypes;
	}

	public void setListStatuts(List<SelectItem> listTypes) {
		this.listTypes = listTypes;
	}
	public String goToDeleteClient() {
		context= FacesContext.getCurrentInstance().getExternalContext();
		request = (HttpServletRequest)context.getRequest();
		try {
			clientService.remove(client);
			listClients = clientService.getAllClients();
			action = "add";
			context.redirect(request.getContextPath()
					+ "/pages/clients.jsf");
		} catch (IOException e) {
			e.printStackTrace();
		}
		client = new Client();
		return "";
	}
	
	public String saveOrUpdateClient()
	{
		context= FacesContext.getCurrentInstance().getExternalContext();
		request = (HttpServletRequest)context.getRequest();
		try {
			client.setDateCreate(new Date()); 
			clientService.saveOrUpdate(client);
			listClients = clientService.getAllClients();
			upload = true;
			action = "add";
			context.redirect(request.getContextPath()
					+ "/pages/clients.jsf");
		} catch (IOException e) {
			e.printStackTrace();
		}
		client = new Client();
		return "";
	}	
	
	
	public String goToAddClient()
	{
		client = new Client();
		//chantier.setStatut("C"); 
		context= FacesContext.getCurrentInstance().getExternalContext();
		request = (HttpServletRequest)context.getRequest();
		try {
			context.redirect(request.getContextPath()
			           + "/pages/client.jsf");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	public String goToUpdateClient()
	{
		context= FacesContext.getCurrentInstance().getExternalContext();
		request = (HttpServletRequest)context.getRequest();
		try {
			context.redirect(request.getContextPath()
					+ "/pages/client.jsf");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public String retourAuClient()
	{
		context = FacesContext.getCurrentInstance().getExternalContext();
		request = (HttpServletRequest)context.getRequest();
		listClients = clientService.getAllClients();
		try {
			context.redirect(request.getContextPath()
					+ "/pages/clients.jsf");
		} catch (IOException e) {
			e.printStackTrace();
		}
		client = new Client();
		return "";
	}
	

	public void exportResults() {
		try {
			DateFormat dateFormatCell = new SimpleDateFormat("dd/MM/yyyy");
			DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
			String date = dateFormat.format(new Date());
			
			String fileBaseName = "client_" + date;
			String filePath = fileBaseName + ".xls";
			int i = 1;
			HSSFWorkbook hwb = new HSSFWorkbook();
			HSSFSheet sheet = hwb.createSheet(fileBaseName);

			HSSFRow rowhead = sheet.createRow((short) 0);
			rowhead.createCell((short) 0).setCellValue("#id");
			rowhead.createCell((short) 1).setCellValue("Nom");
			rowhead.createCell((short) 2).setCellValue("Prenom");
			rowhead.createCell((short) 3).setCellValue("Email");
			rowhead.createCell((short) 4).setCellValue("Telephone");
			rowhead.createCell((short) 5).setCellValue("Telephone fix");
			rowhead.createCell((short) 6).setCellValue("Fax");
			rowhead.createCell((short) 7).setCellValue("Ville");
			rowhead.createCell((short) 8).setCellValue("Adresse");
			rowhead.createCell((short) 9).setCellValue("Date creation");

			for (Client clt : listClients) {
				HSSFRow row = sheet.createRow((short) i);
				if (clt.getId() != null) {
					row.createCell((short) 0).setCellValue(clt.getId());
				} else {
					row.createCell((short) 0).setCellValue("");
				}
				row.createCell((short) 1).setCellValue(
						ExportUtil.getCellValue(clt.getNom()));
				row.createCell((short) 2).setCellValue(
							ExportUtil.getCellValue(clt.getPrenom()));
				row.createCell((short) 3).setCellValue(
						ExportUtil.getCellValue(clt.getEmail()));
				row.createCell((short) 4)
							.setCellValue(ExportUtil.getCellValue(clt.getMobile()));
				row.createCell((short) 5).setCellValue(
							clt.getTelephone());
				row.createCell((short) 5).setCellValue(
						clt.getFax());
				row.createCell((short) 7).setCellValue(
						ExportUtil.getCellValue(clt.getVille()));
				row.createCell((short) 8).setCellValue(
						ExportUtil.getCellValue(clt.getAdress()));
				if (clt.getDateCreate() != null) {
					row.createCell((short) 9).setCellValue(dateFormatCell.format(clt.getDateCreate()));
				} else {
					row.createCell((short) 9).setCellValue("");
				}
				i++;
			}

			FileOutputStream fileOut = new FileOutputStream(filePath);
			hwb.write(fileOut);
			fileOut.close();

			ExportUtil.prepareDownload(filePath);
		} catch (Exception ex) {
			ex.fillInStackTrace();
		}
	}
	
	public List<SelectItem> getListNomComplet() {
		listNomComplet = new ArrayList<SelectItem>();
		if(listNomComplet == null || listNomComplet.isEmpty() || upload)
		for(Client value :  clientService.getAllClients())
		{
			listNomComplet.add(new SelectItem(value, value.getNomComplet()));
		}
		upload = false;
		return listNomComplet;
	}

	public void setListNomComplet(List<SelectItem> listNomComplet) {
		this.listNomComplet = listNomComplet;
	}

	public List<Client> getListClients() {
		return listClients;
	}

	public void setListClients(List<Client> listClients) {
		this.listClients = listClients;
	}

	public Client getClient() {
		return client;
	}
	public void setClient(Client client) {
		this.client = client;
	}
	public IClientService getClientService() {
		return clientService;
	}
	public void setClientService(IClientService clientService) {
		this.clientService = clientService;
	}
	public ErrorHandler getErrorHandler() {
		return errorHandler;
	}
	public void setErrorHandler(ErrorHandler errorHandler) {
		this.errorHandler = errorHandler;
	}
	
}
